/**
 * 
 */
package com.fita.admin.web.controller.client;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.fita.admin.entity.search.client.ClientSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.agent.AgentService;
import com.fita.admin.service.client.ClientInterviewRecordService;
import com.fita.admin.service.client.ClientService;
import com.fita.admin.web.controller.view.Excel2TemplateView;
import com.fita.admin.web.resolver.Secure;
import com.fita.entity.agent.Agent;
import com.fita.entity.client.Client;
import com.fita.entity.client.ClientInterviewRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 客户列表
 * 
 * @author Guangli Yan
 *
 */
@Controller
@RequestMapping(path = "/clients")
@MenuSetting("menu-client")
public class ClientController {

    private final static Logger logger = LoggerFactory.getLogger(ClientController.class);

    @Autowired
    private ClientService clientService;

    @Autowired
    private ClientInterviewRecordService clientInterviewRecordService;

    @Autowired
    private AgentService agentService;

    /**
     * @param request 
     * @return
     */
    @GetMapping(path = "")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView list(HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("client/client/client-list");
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
        
        int count = clientService.count(Client.class);

        if (count > 0){

            List<Client> clients = clientService.listByPage(Client.class, page.with(count));

            modelAndView.addObject("clients", clients);

            modelAndView.addObject("page", page);
        }
        return modelAndView;
    }
    
    /**
     * @param clientId
     * @return
     */
    @GetMapping(path = "/{clientId}")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView view(@PathVariable Long clientId) {
        
        ModelAndView modelAndView = new ModelAndView("client/client/client-view");
        
        Client client = clientService.load(Client.class, clientId);

        modelAndView.addObject("client", client);

        List<ClientInterviewRecord> clientInterviewRecords = clientInterviewRecordService.loadByClient(client);

        modelAndView.addObject("clientInterviewRecords", clientInterviewRecords);

        if (client.getAgent() != null){
            int sales = clientService.calculateSales(clientId);
            modelAndView.addObject("sales", sales);
        }
        return modelAndView;
    }
    
    /**
     * @return
     */
    @GetMapping(path = "/add")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView add(HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("client/client/client-add");
        
        return modelAndView;
    }
    
    /**
     * @return
     */
    @PostMapping(path = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @MenuSetting("submenu-client-list-management")
    public HttpResult onAdd(@Secure Login login, Client client) {
        try {
            clientService.addClient(client, login);
            return new HttpResult().success().message("添加成功");
        } catch (BusinessException e) {
            return new HttpResult().fail(e.getCode()).message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onAdd() error [{}]", e);
            return new HttpResult().fail("500").message("添加错误");
    }
    }
    
    /**
     * @return
     */
    @GetMapping(path = "/{clientId}/edit")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView edit(@PathVariable Long clientId) {
        
        ModelAndView modelAndView = new ModelAndView("client/client/client-edit");
        
        Client client = clientService.load(Client.class, clientId);

        modelAndView.addObject("client", client);

        return modelAndView;
    }
    
    /**
     * @return
     */
    @PatchMapping(path = "/{clientId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @MenuSetting("submenu-client-list-management")
    public HttpResult onEdit(@PathVariable Long clientId, Client client) {
        try {
            clientService.edit(clientId, client);
            return new HttpResult().success().message("修改成功");
        } catch (Exception e) {
            logger.error("#onEdit() error [{}]", e);
            return new HttpResult().fail("500").message("修改失败");
    }
    }
    
    /**
     * @return
     */
    @GetMapping(path = "/export")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView export() {
        
        ModelAndView modelAndView = new ModelAndView("client/client/client-export");
        


        return modelAndView;
    }
    
    /**
     * @return
     */
    @PostMapping(path = "/export")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView onExport(ClientSearch search) {
        
        ModelAndView modelAndView = new ModelAndView(new Excel2TemplateView("report/client-report.xlsx"));
        
        List<Client> clients = clientService.export(search);

        modelAndView.addObject("clients", clients);

        return modelAndView;
    }

    /**
     *
     * @return
     */
    @GetMapping(path = "/{clientId}/bind-agent")
    @MenuSetting("submenu-client-list-management")
    public ModelAndView bindAgent(@PathVariable Long clientId) {

        ModelAndView modelAndView = new ModelAndView("client/client/client-bind-agent");

        List<Agent> agents = agentService.listAll(Agent.class);

        modelAndView.addObject("agents", agents);

        Client client = clientService.load(Client.class, clientId);

        modelAndView.addObject("client", client);

        return modelAndView;
    }

    /**
     * 客户绑定代理
     * @return
     */
    @PostMapping(path = "/{clientId}/bind-agent", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @MenuSetting("submenu-client-list-management")
    public HttpResult onBindAgent(@PathVariable Long clientId,
                                  @RequestParam Long agentId) {
        try {
            clientService.bindAgent(clientId, agentId);
            return new HttpResult().success();
        } catch (Exception e) {
            logger.error("#onBindAgent error , [{}]", e);
            return new HttpResult().fail("500");
        }
    }
}



